'use strict';

const { Controller } = require('egg');
const crypto = require('crypto');
const WXPay = require('../../extend/wxpay');
const urlencode = require('urlencode');
const fs = require('fs');
const wxpay = WXPay({
    appid: 'wx6516e82669c2fe16',
    mch_id: '1641829205',
    partner_key: '342706709xdxl342706709xdxl342706',
    pfx: fs.readFileSync('././apiclient_cert.p12'),
});

class UserController extends Controller {
    async reg() {
        const { ctx, app } = this;
        ctx.validate({
            username: {
                type: 'string',
                required: true,
                desc: '用户名'
            },
            phone: {
                type: 'phone',
                required: true,
                trim: true,
                desc: '手机号'
            },
            password: {
                type: 'string',
                required: true,
                desc: '密码',
                range: {
                    min: 6
                }
            },
            repassword: {
                type: 'string',
                required: true,
                desc: '确认密码',
                range: {
                    min: 6
                }
            },
            code: {
                type: 'int',
                required: true,
                desc: '验证码'
            }
        }, {
            equals: [
                ['password', 'repassword']
            ]
        });
        const { username, phone, password, repassword, code } = ctx.request.body;
        if (await app.model.User.findOne({ where: { username } })) {
            return ctx.apiError('用户名已存在');
        };
        if (await app.model.User.findOne({ where: { phone } })) {
            return ctx.apiError('该手机号已绑定其他用户');
        };
        let has = await ctx.service.cache.get('sms_' + phone);
        if (parseInt(has) !== code) {
            return ctx.apiError('验证码不正确，请重试！')
        };
        let user = await app.model.User.create({
            username,
            password,
            phone
        });
        await ctx.service.cache.remove('sms_' + phone);
        if (!user) {
            return ctx.apiError('创建用户失败，请重试！');
        };
        delete user.password;
        ctx.apiSuccess(user);
    };

    async login() {
        const { ctx, app } = this;
        ctx.validate({
            phone: {
                type: 'phone',
                required: true,
                desc: '手机号'
            },
            password: {
                type: 'string',
                required: false,
                desc: '密码',
            },
            code: {
                type: 'int',
                required: false,
                desc: '验证码'
            }
        });
        let { phone, password, code } = ctx.request.body;
        let user = await app.model.User.findOne({
            where: {
                phone
            }
        });
        if (!user) {
            return ctx.apiError('用户不存在或者已封禁')
        }
        if (password) {
            console.log(password == user.password);
            await this.checkPassword(password, user.password);
        } else {
            let has = await ctx.service.cache.get('sms_' + phone);
            if (parseInt(has) !== code) {
                ctx.throw(400, '验证码错误')
            };
        };
        user = JSON.parse(JSON.stringify(user));
        // 生成token
        let token = ctx.getToken(user);
        user.token = token;

        delete user.password;
        // 加入缓存中
        if (!await this.service.cache.set('user_' + user.id, token)) {
            ctx.throw(400, '登录失败');
        }
        // 返回用户信息和token
        return ctx.apiSuccess(user);
    };

    // 验证密码
    async checkPassword(password, hash_password) {
        // 先对需要验证的密码进行加密
        const hmac = crypto.createHash("sha256", this.app.config.crypto.secret);
        hmac.update(password);
        password = hmac.digest("hex");
        let res = password === hash_password;
        if (!res) {
            this.ctx.throw(400, '密码错误');
        }
        return true;
    }

    async getCode() {
        const { ctx, app } = this;
        ctx.validate({
            phone: {
                type: 'phone',
                trim: true,
                required: true,
                desc: '手机号'
            }
        });
        //1.接收手机号码
        const { phone } = ctx.request.body;
        //3.判断是否已经获取过验证码(判断缓存中是否存在当前手机号的验证码，有则提示"你已经获取过验证码了"),防止别有用心之人频繁验证，避免短信费用过高
        let has = await ctx.service.cache.get('sms_' + phone);
        if (has) {
            ctx.throw(200, '您已获取过验证码了');
        }

        //4.生成4~6位数随机数字 生成六位随机验证码
        let code = Math.random().toString().slice(-6);
        //5.发送短信(阿里大于)
        let res = await ctx.sms.sendSMS({
                PhoneNumbers: phone, //手机号码
                SignName: '万能侠', //签名
                TemplateCode: 'SMS_227247454', // 模板
                TemplateParam: `{"code":"${code}"}`
            })
            //6.手机号=>验证码的形式保存在缓存中(60秒)
        if (!await this.service.cache.set('sms_' + phone, code, 60 * 5)) {
            ctx.throw(200, '验证失败');
        }
        //7.提示成功
        ctx.apiSuccess(res);
    }
    async usercollectList() {
        const { ctx, app } = this;
        const userId = ctx.authUser.id;
        let usercollectList = await app.model.Usercollect.findAll({
            where: {
                userid: userId
            },
            include: [{
                model: app.model.Courses,
                as: 'courseInfo'
            }]
        });
        ctx.apiSuccess(usercollectList);
    }

    async addUsercollect() {
            const { ctx, app } = this;
            const userId = ctx.authUser.id;
            const { courseid } = ctx.params;
            let usercollectList = await app.model.Usercollect.findOne({
                where: {
                    userid: userId,
                    courseid
                }
            });
            if (usercollectList) {
                await usercollectList.destroy();
                return ctx.apiSuccess('取消收藏');
            }
            await app.model.Usercollect.create({
                userid: userId,
                courseid
            });
            ctx.apiSuccess('收藏成功');
        }
        // 微信支付
    async coursewxpay() {
            const { ctx, app } = this;
            let user_id = ctx.authUser.id

            ctx.validate({
                id: {
                    type: "int",
                    required: true,
                    desc: "課程id"
                }
            })

            const { id } = ctx.request.body
            let courses = await app.model.Courses.findOne({ id });
            if (!courses) {
                return ctx.apiFail('不存在此課程')
            }

            // 创建订单
            let no = ctx.randomString(20)
            let order = await app.model.Order.create({
                no,
                user_id,
                price: courses.sellingprice,
                commodityid: id,
                type: 1,
                commodityname: courses.coursesname,
                commodityimg: courses.coursescoverimg
            })

            if (!order) {
                return ctx.apiFail('创建订单失败')
            }
            // console.log(order)
            // 支付
            let result = await app.tenpay.getAppParams({
                out_trade_no: no,
                body: '购买商品',
                total_fee: order.price * 100,
                trade_type: "MWEB"
            })
            console.log(result);
            // console.log(result)
            //https://api.mch.weixin.qq.com/v3/pay/transactions/h5
            // var formData = "<xml>";
            // formData += "<appid>" + 'wx6516e82669c2fe16' + "</appid>"; //appid
            // formData += "<body><![CDATA[" + "微信支付" + "]]></body>";
            // formData += "<mch_id>" + '1641829205' + "</mch_id>"; //商户号
            // formData += "<nonce_str>" + result.nonce_str + "</nonce_str>"; //随机字符串，不长于32位。
            // formData += "<notify_url>" + 'dbqjw.top:7001/config/notify' + "</notify_url>";
            // formData += "<out_trade_no>" + result.nonce_str + "</out_trade_no>";
            // formData += "<spbill_create_ip>" + '113.246.32.110' + "</spbill_create_ip>";
            // formData += "<total_fee>" + '1' + "</total_fee>";
            // formData += "<trade_type>" + 'MWEB' + "</trade_type>";
            // formData += "<sign>" + result.sign + "</sign>";
            // formData += "</xml>";
            // let res = await ctx.curl('https://api.mch.weixin.qq.com/pay/unifiedorder', {
            //     method: 'POST',
            //     // dataType: "json",
            //     headers: {
            //         // 'content-type': 'json'
            //         // "content-type": "application/json; charset=utf-8",
            //     },
            //     // data: {
            //     //     appid: 'wx6516e82669c2fe16',
            //     //     mch_id: '1641829205',
            //     //     out_trade_no: result.noncestr,
            //     //     nonce_str: result.noncestr,
            //     //     sign: result.sign,
            //     //     body: '心定心理',
            //     //     // total_fee:res.data.data.noncestr,
            //     //     total_fee: 1,
            //     //     spbill_create_ip: '113.246.32.110',
            //     //     notify_url: 'dbqjw.top:7001/config/notify',
            //     //     trade_type: 'MWEB',
            //     //     scene_info: { "h5_info": { "type": "Wap", "wap_url": "https://pay.qq.com", "wap_name": "课程充值" } }
            //     // }
            //     // data: {
            //     //     "mchid": "1641829205",
            //     //     "out_trade_no": result.noncestr,
            //     //     "appid": "wx6516e82669c2fe16",
            //     //     "description": "Image形象店-深圳腾大-QQ公仔",
            //     //     "notify_url": "dbqjw.top:7001/config/notify",
            //     //     "amount": {
            //     //         "total": 1,
            //     //         "currency": "CNY"
            //     //     },
            //     //     "scene_info": {
            //     //         "payer_client_ip": "127.0.0.1",
            //     //         "h5_info": {
            //     //             "type": "Wap"
            //     //         }
            //     //     }
            //     // }
            //     data: formData
            // })
            const results = await wxpay.createOutH5Pay({
                body: 'H5支付测试', // 商品描述
                out_trade_no: result.noncestr, //订单编号
                total_fee: 1, //支付总金额（单位：分）
                spbill_create_ip: '192.168.2.56', //付款ip
                notify_url: 'http://hnsxdxl.com/config/notify', //支付回调地址
                trade_type: 'NATIVE', //支付方式 扫码付
            });

            if (results.return_code == "SUCCESS") {
                // 渲染静态页面，模拟提交表单
                // 此处需要添加支付完成或取消返回的路径
                results.mweb_url = results.mweb_url + "&redirect_url=" + urlencode("http://hnsxdxl.com/pages/my/index")
            }

            console.log(results);
            // console.log(res)
            ctx.apiSuccess(results)
        }
        // 微信支付
    async appraisalwxpay() {
            const { ctx, app } = this;
            let user_id = ctx.authUser.id

            ctx.validate({
                id: {
                    type: "int",
                    required: true,
                    desc: "测评id"
                }
            })

            const { id } = ctx.request.body
            let courses = await app.model.Appraisal.findOne({ id });
            if (!courses) {
                return ctx.apiFail('不存在此测评')
            }

            // 创建订单
            let no = ctx.randomString(20)
            let order = await app.model.Order.create({
                no,
                user_id,
                price: courses.sellingprice,
                commodityid: id,
                type: 2,
                commodityname: courses.appraisalname,
                commodityimg: courses.appraisalcoverimg
            })

            if (!order) {
                return ctx.apiFail('创建订单失败')
            }
            // 支付
            let result = await app.tenpay.getAppParams({
                out_trade_no: no,
                body: '购买商品',
                total_fee: order.price * 100,
                trade_type: "APP"
            })
            console.log(result)

            ctx.apiSuccess(result)
        }
        // 支付回调
    async notify() {
        const { ctx, app, service } = this
        let info = ctx.request.weixin;

        if (!info || info.result_code !== 'SUCCESS') {
            return ctx.reply('支付失败')
        }

        // 查询当前订单
        let order = await app.model.Order.findOne({
            where: {
                no: info.out_trade_no
            }
        })

        if (!order) {
            return ctx.reply('订单不存在')
        }

        // 修改订单状态
        order.status = 'success'
        order.save()

        // 修改用户余额
        // let user = await  app.model.user.exist(order.user_id)
        // if (user) {
        //     user.coin += info.total_fee / 100
        //     user.save()
        // }
        if (order.type === 1) {
            let course = await app.model.Usercourse.create({
                userid: user_id,
                courseid: order.commodityid
            })
        }
        if (order.type === 2) {
            let appraisal = await app.model.Userappraisal.create({
                userid: user_id,
                appraisalid: order.commodityid
            })
        }
        ctx.reply()
    }
    async orderList() {
        const { ctx, app } = this;
        let user_id = ctx.authUser.id;
        let list = await app.model.Order.findAll({
            where: {
                user_id: user_id
            }
        })
        return ctx.apiSuccess(list);
    }
    async courseList() {
        const { ctx, app } = this;
        let user_id = ctx.authUser.id;
        let list = await app.model.Usercourse.findAll({
            where: {
                userid: user_id
            }
        })
        return ctx.apiSuccess(list);
    }
    async appraisalList() {
        const { ctx, app } = this;
        let user_id = ctx.authUser.id;
        let list = await app.model.Userappraisal.findAll({
            where: {
                userid: user_id
            }
        })
        return ctx.apiSuccess(list);
    }
    async coursevideoList() {
        const { ctx, app } = this;
        let user_id = ctx.authUser.id;
        ctx.validate({
            id: {
                type: "int",
                required: true,
                desc: "课程id"
            }
        })
        let { id } = ctx.request.body;
        let appraisal = await app.model.Usercourse.findOne({
            where: {
                id,
                userid: user_id,
            }
        });
        if (!appraisal) {
            return ctx.apiError("已使用或者没有购买课程")
        }
        appraisal = JSON.parse(JSON.stringify(appraisal));

        let videoList = await app.model.Video.findAll({
            where: {
                course_id: appraisal.courseid
            }
        });
        return ctx.apiSuccess(videoList);
    }
    async useappraisal() {
        const { ctx, app } = this;
        let user_id = ctx.authUser.id;
        ctx.validate({
            id: {
                type: "int",
                required: true,
                desc: "测评id"
            }
        })
        let { id } = ctx.request.body;
        let appraisal = await app.model.Userappraisal.findOne({
            where: {
                id,
                userid: user_id,
                use: 0
            }
        });
        if (!appraisal) {
            return ctx.apiError("已使用或者没有购买测评")
        }
        appraisal = JSON.parse(JSON.stringify(appraisal));
        await app.model.Userappraisal.update({
            use: 1
        }, {
            where: {
                id,
                userid: user_id
            }
        });
        let topicList = await app.model.Topic.findAll({
            where: {
                appraisal_id: appraisal.appraisalid
            }
        });
        return ctx.apiSuccess(topicList);
    }
}

module.exports = UserController;